from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import urllib.request as ur
from re import search, findall, sub
from random import choice


class Inquire:
    def __init__(self, model, good=None):
        self.model = model
        self.good = good

    def get_all(self):
        return self.model.objects.all().values_list('goods__name',
                                                    'room__tower__name',
                                                    'room__floor__name',
                                                    'room__room',
                                                    'user__name',
                                                    'number',
                                                    'unit',
                                                    'id',)

    def get_inquire(self):
        return self.model.objects.filter(goods=self.good).values_list('goods__name',
                                                                      'room__tower__name',
                                                                      'room__floor__name',
                                                                      'room__room',
                                                                      'user__name',
                                                                      'number',
                                                                      'unit',
                                                                      'id',)

    def get_page(self, page=1, list_obj=None):
        paginator = Paginator(list(list_obj), 15)  # 在这里调整每一页几条数据
        try:
            return paginator.page(page), paginator.num_pages
        except PageNotAnInteger:  # 如果页面不是整数，则提交第一页。
            print('提交第一页')
            return paginator.page(1), paginator.num_pages
        except EmptyPage:  # 如果页面超出范围(例如9999)，提交结果的最后一页。
            print('提交最后一页')
            return paginator.page(paginator.num_pages), paginator.num_pages


url = 'http://jandan.net/duan'
text = []  # 全段子列表
head = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26'
                      ' Safari/537.36 Core/1.63.6735.400 QQBrowser/10.2.2614.400'}


def get_all_text():
    html = ur.urlopen(ur.Request(url, headers=head)).read().decode('utf-8')  # 请求网页
    li = search('<ol class="commentlist"[\s\S]*?</ol>', html)[0]  # 获取全部列表
    list_li = findall('<li id="comment-[\s\S]*?举报[\s\S]*?吐槽[\s\S]*?</li>', str(li))  # 获取段子列表
    for i in list_li:
        text.append(sub('(<br />)|(<br>)|(&#8230)', '', search('<p>[\s\S]*?</p>', i)[0][3:-4]))  # 取出全部段子
    return text


def get_random_text():
    return choice(get_all_text())


if __name__ == '__main__':
    print(get_random_text())
